package com.stormragetech.init.sign;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class InitSignHandle {

	public <T> String initSign(T t, InitParams params) {

		if (null == t || null == params || params.isEmpty()) {
			return null;
		}

		Map<String, String> map = domainToMap(t, params);

		SortedMap<String, String> sort = sort(map, params);

		String source = source(sort);

		String sign = encode(source, params);

		return sign;

	}

	public <T> Map<String, String> domainToMap(T t, InitParams params) {

		Map<String, String> map = new HashMap<String, String>();

		try {

			for (String fieldName : params.getProperties()) {

				PropertyDescriptor property = new PropertyDescriptor(fieldName, t.getClass());
				Method getMethod = property.getReadMethod();
				String value = convertValue(getMethod.invoke(t));
				map.put(fieldName, value);

			}

		} catch (Exception e) {
			System.out.println(" >>>>>>>>>>>>>> 转换发生错误 <<<<<<<<<<<<< ");
			return null;
		}

		return map;

	}

	private String convertValue(Object obj) {

		String value = null;

		if (obj instanceof Date) {
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			value = format.format(obj);
		} else {
			value = obj.toString();
		}

		return value;

	}

	private SortedMap<String, String> sort(Map<String, String> map, InitParams params) {

		StormragetechValueComparator comparator = new StormragetechValueComparator();
		SortedMap<String, String> sort = new TreeMap<String, String>(comparator);

		if (params.getOrder().equals(0)) {
			sort = new TreeMap<String, String>();
			sort.putAll(map);
		} else {
			sort = new TreeMap<String, String>(comparator);
			sort.putAll(map);
		}

		return sort;

	}

	private String source(SortedMap<String, String> sort) {

		StringBuffer source = new StringBuffer("");
		Set<String> keySet = sort.keySet();
		int i = 1;
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			source.append(key);
			source.append("=");
			source.append(sort.get(key));
			if (i < keySet.size()) {
				source.append("&");
			}
			i++;
		}

		return source.toString();

	}

	private String encode(String source, InitParams params) {

		String sign = "";

		for (String enc : params.getEncode()) {
			if (enc.equals("MD5")) {

			}
			if (enc.equals("SHA1")) {

			}
		}

		return sign;

	}

	static class StormragetechValueComparator implements Comparator<String> {

		@Override
		public int compare(String arg0, String arg1) {
			return arg1.compareTo(arg0);
		}
	}

}
